package top.ibiji.shiro.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ibiji.shiro.model.SysUser;
import top.ibiji.shiro.service.SysUserService;
import top.ibiji.shiro.utils.CustomTokenUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Service
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    private SysUserService sysUserService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 权限验证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        System.out.println("principalCollection---->" + principalCollection);
        String username = CustomTokenUtils.getUsernameFromToken(principalCollection.toString());

        SysUser user = sysUserService.findByName(username);

        simpleAuthorizationInfo.addRole(user.getNickName());

        Set<String> perSet = new HashSet<>(Arrays.asList(user.getPer().split(",")));

        simpleAuthorizationInfo.addStringPermissions(perSet);

        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = authenticationToken.getCredentials().toString();

        String username = CustomTokenUtils.getUsernameFromToken(token);

        if (username == null) {
            throw new AuthenticationException("token invalid");
        }

        SysUser user = sysUserService.findByName(username);

        if (user == null) {
            throw new AuthenticationException("User didn't existed!");
        }

        if (!CustomTokenUtils.verify(token, user.getName(), user.getPassword())) {

        }


        return new SimpleAuthenticationInfo(token, token, "my_shiro_realm");
    }
}
